import sysUserApi from '@/api/system/systemuser'
import { getToken, setToken, removeToken } from '@/utils/auth'

import { resetRouter } from '@/router'
import { constantRoutes } from '@/router'

import Layout from '@/layout'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      sysUserApi.login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        const token = data
        commit('SET_TOKEN', token)
        setToken(token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      sysUserApi.getInfo().then(response => {
        const data = response.data

        if (!data) {
          reject('该用户没有被授权，请联系管理员授权用户.')
        }

        const { roles, username, nickname, avatar } = data

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }

        // 定义用户路由表
        const routerTree = new Array()

        // 可有可无的修改。适配如果有一个用户可以登录系统，但是却没有分任何菜单权限
        const _menus = data.perms.menus
        if (_menus) {
          _menus.forEach((item) => {
            // eslint-disable-next-line eqeqeq
            if (item.pid == 0) {
              var routerItem = {
                name: item.name,
                sort: item.sort,
                path: item.path,
                hidden: item.hidden,
                component: Layout,
                meta: { title: item.name, icon: item.iconCls },
                children: getChildren(item.id, _menus)
              }
              routerTree.push(routerItem)
            }
          })
        }

        routerTree.push({ path: '*', redirect: '/err', hidden: true })

        //  排序
        const routers = bubble_sort(routerTree)

        commit('SET_ROLES', roles)
        commit('SET_NAME', nickname || username)
        commit('SET_AVATAR', avatar)
        commit('SET_ROUTES', routers)

        resolve(routers)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, dispatch, state }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

function loadView(view) {
  // 路由懒加载
  // return () => import(`@/views/${view}`)
  return () => Promise.resolve(require(`@/views/${view}`).default)
}

function getChildren(pid, items) {
  const childrenItems = []
  items.forEach((item) => {
    // eslint-disable-next-line eqeqeq
    if (item.pid == pid) {
      // console.log(getChildren(item.id, items))
      const tree = {
        sort: item.sort,
        name: item.name,
        path: item.path,
        hidden: item.hidden,
        component: loadView(item.component),
        meta: { title: item.name, icon: item.iconCls }
      }
      if (getChildren(item.id, items).length > 1) {
        tree.children = getChildren(item.id, items)
      }

      childrenItems.push(tree)
    }
  })
  return bubble_sort(childrenItems)
}
// 冒泡排序
function bubble_sort(arr) {
  const len = arr.length
  let count
  let tmp
  for (let i = len; i > 0; i--) {
    count = 0
    for (let i = 0; i < len; i++) {
      if (arr[i] && arr[i + 1] && arr[i].sort > arr[i + 1].sort) {
        tmp = arr[i]
        arr[i] = arr[i + 1]
        arr[i + 1] = tmp
        count++
      }
    }
    // eslint-disable-next-line eqeqeq
    if (count == 0) {
      return arr
    }
  }
  return arr
}
